#include"slist.h"

void slistprint(sltnode* phead)
{
	sltnode* cur = phead;
	while (cur != NULL)
	{
		printf("%d->", cur->data);
		cur = cur->next;
	}
	printf("NULL\n");
}

sltnode* buynode(datatype x)
{
	sltnode* newnode = (sltnode*)malloc(sizeof(sltnode));
	if (newnode == NULL)
	{
		perror("newnode fail");
		return NULL;
	}
	newnode->data = x;
	newnode->next = NULL;
	return newnode;
}
void pushfront(sltnode** pphead, datatype x)
{
	sltnode* newnode = buynode(x);

	newnode->next = *pphead;
	*pphead = newnode;
}
void pushback(sltnode** pphead, datatype x)
{
	sltnode* newnode = buynode(x);

	if (*pphead == NULL)
	{
		*pphead = newnode;
	}
	else
	{
		sltnode* tail = *pphead;
		while (tail->next != NULL)
		{
			tail = tail->next;
		}
		tail->next = newnode;
	}
}

void popfront(sltnode** pphead)
{
	sltnode* node = *pphead;
	*pphead = (*pphead)->next;
	free(node);

}

void popback(sltnode** pphead)
{
	/*sltnode* tail = *pphead;
	sltnode* prev = NULL;
	while (tail->next != NULL)
	{
		prev = tail;
		tail = tail->next;
	}
	free(tail);
	prev->next = NULL;*/

	assert(*pphead);

	if ((*pphead)->next == NULL)
	{
		free(*pphead);
	}
	else
	{
		sltnode* tail = *pphead;
		while (tail->next->next)
		{
			tail = tail->next;
		}
		free(tail->next);
		tail->next = NULL;
	}

}